package com.tudouji.project.produce.service.impl;

import com.flow.service.pojo.BasePojo;
import com.flow.service.pojo.ResultParam;
import com.flow.service.pojo.result.FlowResult;
import com.flow.service.process.service.IFlowBaseService;
import com.github.pagehelper.PageHelper;
import com.tudouji.common.utils.DateUtils;
import com.tudouji.common.utils.IdUtils;
import com.tudouji.common.utils.SecurityUtils;
import com.tudouji.common.utils.sql.SqlUtil;
import com.tudouji.framework.web.domain.AjaxResult;
import com.tudouji.framework.web.page.PageDomain;
import com.tudouji.framework.web.page.TableSupport;
import com.tudouji.project.bill.domain.Whinform;
import com.tudouji.project.bill.domain.Whinformitem;
import com.tudouji.project.bill.service.impl.WhinformServiceImpl;
import com.tudouji.project.bill.service.impl.WhoutformServiceImpl;
import com.tudouji.project.flow.utils.FlowProcessUtil;
import com.tudouji.project.organization.domain.Department;
import com.tudouji.project.organization.domain.Organization;
import com.tudouji.project.organization.mapper.DepartmentMapper;
import com.tudouji.project.organization.mapper.OrganizationMapper;
import com.tudouji.project.permission.domain.Salespermission;
import com.tudouji.project.permission.service.impl.SalespermissionServiceImpl;
import com.tudouji.project.produce.domain.Materialretapply;
import com.tudouji.project.produce.domain.Matretapplyitem;
import com.tudouji.project.produce.domain.Pickinglist;
import com.tudouji.project.produce.mapper.MaterialretapplyMapper;
import com.tudouji.project.produce.mapper.MatretapplyitemMapper;
import com.tudouji.project.produce.mapper.PickinglistMapper;
import com.tudouji.project.produce.service.IMaterialretapplyService;
import com.tudouji.project.store.domain.Storeroom;
import com.tudouji.project.store.mapper.StorehouseroomMapper;
import com.tudouji.project.store.mapper.StoreroomMapper;
import com.tudouji.project.system.domain.SysUser;
import com.tudouji.project.system.service.impl.BusinesscodeServiceImpl;
import org.apache.commons.beanutils.ConvertUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import static com.tudouji.framework.web.domain.AjaxResult.CODE_TAG;

/**
 * 报废Service业务层处理
 *
 * @author tudouji
 * @date 2022-06-01
 */
@Service
public class MaterialretapplyServiceImpl implements IMaterialretapplyService, IFlowBaseService
{
    @Autowired
    private MaterialretapplyMapper materialretapplyMapper;
    @Autowired
    private MatretapplyitemMapper matretapplyitemMapper;
    @Autowired
    private PickinglistMapper pickinglistMapper;
    @Autowired
    private PickinglistServiceImpl pickinglistService;
    @Autowired
    private BusinesscodeServiceImpl businesscodeService;
    @Autowired
    private StoreroomMapper storeroomMapper;
    @Autowired
    private StorehouseroomMapper storehouseroomMapper;
    @Autowired
    private WhoutformServiceImpl whoutformService;
    @Autowired
    private DepartmentMapper departmentMapper;
    @Autowired
    private OrganizationMapper organizationMapper;
    @Autowired
    private FlowProcessUtil processUtils;
    @Autowired
    private WhinformServiceImpl whinformService;
    @Autowired
    private SalespermissionServiceImpl permissionService;
    /**
     * 查询报废
     *
     * @param guid 报废ID
     * @return 报废
     */
    @Override
    public Materialretapply selectMaterialretapplyById(String guid)
    {
        return materialretapplyMapper.selectMaterialretapplyById(guid);
    }
    @Override
    public Materialretapply selectMaterialretapplyByNewId(Long guid)
    {
        return materialretapplyMapper.selectMaterialretapplyByNewId(guid);
    }

    /**
     * 查询报废列表
     *
     * @param materialretapply 报废
     * @return 报废
     */
    @Override
    public List<Materialretapply> selectMaterialretapplyList(Materialretapply materialretapply)
    {
        return materialretapplyMapper.selectMaterialretapplyList(materialretapply);
    }
    /**
     * 设置请求分页数据
     */
    protected void startPage()
    {
        PageDomain pageDomain = TableSupport.buildPageRequest();
        Integer pageNum = pageDomain.getPageNum();
        Integer pageSize = pageDomain.getPageSize();
        if (com.tudouji.common.utils.StringUtils.isNotNull(pageNum) && com.tudouji.common.utils.StringUtils.isNotNull(pageSize))
        {
            String orderBy = SqlUtil.escapeOrderBySql(pageDomain.getOrderBy());
            PageHelper.startPage(pageNum, pageSize, orderBy);
        }
    }

    @Override
    public List<Materialretapply> selectMaterialretapplyList(Materialretapply materialretapply, String status, String functionType) {
        SysUser sysUser = SecurityUtils.getLoginUser().getUser();
        if (materialretapply == null) {
            materialretapply = new Materialretapply();
        }

        if (org.apache.commons.lang.StringUtils.isNotBlank(status)) {
            if (status.equals("00")) {// 待处理
                materialretapply.setCreateBy(sysUser.getUserId());
                startPage();
                return materialretapplyMapper.selectMaterialretapplyPendingList(materialretapply);
            } else {
                String[] sts = status.split(",");
                Integer[] stss = (Integer[]) ConvertUtils.convert(sts, Integer.class);
                materialretapply.setStats(stss);
            }
        }
        //查询是否有全局权限
        List<Salespermission> permissions = permissionService.getPermByScAndFuncSYS(sysUser.getUserId(), functionType, "4");
        if (permissions.size() > 0) {
            startPage();
            return materialretapplyMapper.selectMaterialretapplyList(materialretapply);
        } else {
            materialretapply.setCreateBy(sysUser.getUserId());
            // 是否有组织权限
            List<Salespermission> permissionsOrg = permissionService
                    .getPermByScAndFuncSYS(sysUser.getUserId(), functionType, "7");
            //是否有部门权限
            permissions = permissionService.getPermByScAndFuncSYS(sysUser.getUserId(), functionType, "2");

            startPage();
            if (permissions.size() > 0 || permissionsOrg.size() > 0) {
                String[] deptids = new String[permissions.size()];
                for (int i = 0; i < permissions.size(); i++) {
                    deptids[i] = permissions.get(i).getDepartid();
                }
                String[] roomids = new String[permissionsOrg.size()];
                for (int i = 0; i < permissionsOrg.size(); i++) {
                    roomids[i] = permissionsOrg.get(i).getSrguid();
                }
                materialretapply.setRoomids(roomids);
                materialretapply.setDepids(deptids);
                return materialretapplyMapper.selectMaterialretapplyByDep(materialretapply);
            } else {
                //查询个人的
                return materialretapplyMapper.selectMaterialretapplyByUser(materialretapply);
            }
        }
    }

    /**
     * 新增报废
     *
     * @param materialretapply 报废
     * @return 结果
     */
    @Override
    public int insertMaterialretapply(Materialretapply materialretapply)
    {
        return materialretapplyMapper.insertMaterialretapply(materialretapply);
    }

    /**
     * 修改报废
     *
     * @param materialretapply 报废
     * @return 结果
     */
    @Override
    public int updateMaterialretapply(Materialretapply materialretapply)
    {
        return materialretapplyMapper.updateMaterialretapply(materialretapply);
    }

    /**
     * 批量删除报废
     *
     * @param guids 需要删除的报废ID
     * @return 结果
     */
    @Override
    public int deleteMaterialretapplyByIds(String[] guids)
    {
        return materialretapplyMapper.deleteMaterialretapplyByIds(guids);
    }

    /**
     * 删除报废信息
     *
     * @param guid 报废ID
     * @return 结果
     */
    @Override
    public int deleteMaterialretapplyById(String guid)
    {
        return materialretapplyMapper.deleteMaterialretapplyById(guid);
    }

    @Override
    @Transactional(propagation = Propagation.REQUIRED, rollbackFor = {Exception.class})
    public AjaxResult save(Materialretapply materialretapply, String fileIds) {
        SysUser sysUser = SecurityUtils.getLoginUser().getUser();

        Storeroom room = storeroomMapper.selectStoreroomByGuid(materialretapply.getSrguid());
        Department department = departmentMapper.selectDepartmentById(materialretapply.getDepartid());
        Organization organization =organizationMapper.selectOrganizationById(room.getOrgguid());
        materialretapply.setStrmId(room.getId());
        materialretapply.setOrgguid(room.getOrgguid());
        materialretapply.setOrgId(organization.getId());
        materialretapply.setOrgname(room.getOrgname());
        materialretapply.setCode(businesscodeService.getCode("27"));
        materialretapply.setOperatorid(sysUser.getTuserId());

        String guid = IdUtils.fastSimpleUUID();
        materialretapply.setGuid(guid);
        materialretapply.setDeptId(department.getId());
        materialretapply.setDeptName(department.getName());
        materialretapply.setCreateBy(sysUser.getUserId());
        materialretapply.setCreatetime(DateUtils.getNowDate());
        materialretapply.setFlowid(31L);

        materialretapplyMapper.insertMaterialretapply(materialretapply);
        for (Matretapplyitem itsm : materialretapply.getItems()) {
            itsm.setMatretapplyid(guid);
            itsm.setGuid(IdUtils.fastSimpleUUID());
            matretapplyitemMapper.insertMatretapplyitem(itsm);
        }

        materialretapply.setPlatformId(room.getId());
        FlowResult result = processUtils.defaultStart(processUtils.getStartNode(materialretapply.getFlowid())
                , materialretapply, fileIds, sysUser);
        if (result.getMsg().equals(ResultParam.SUCCESS)) {
            Materialretapply mApply = new Materialretapply();
            mApply.setGuid(guid);
            mApply.setStatus(result.getNextStat());
            materialretapplyMapper.updateMaterialretapply(mApply);
            return AjaxResult.success();
        } else {
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            return AjaxResult.error(result.getMsg());
        }
    }

    @Override
    @Transactional(propagation = Propagation.REQUIRED, rollbackFor = {Exception.class})
    public AjaxResult approval(Long id, String imgids, String opinion, Long taskid) {
        SysUser sysUser = SecurityUtils.getLoginUser().getUser();
        Materialretapply materialretapply = materialretapplyMapper.selectMaterialretapplyByNewId(id);

        materialretapply.setPlatformId(materialretapply.getStrmId());
        FlowResult result = processUtils.defaultApproval(taskid, imgids, opinion, materialretapply
                , sysUser);
        if (result.getMsg().equals(ResultParam.SUCCESS)) {
            Materialretapply mApply = new Materialretapply();
            mApply.setStatus(result.getNextStat());
            mApply.setGuid(materialretapply.getGuid());
            this.updateMaterialretapply(mApply);
            return AjaxResult.success();
        } else {
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            return AjaxResult.error(result.getMsg());
        }
    }

    @Override
    @Transactional(propagation = Propagation.REQUIRED, rollbackFor = {Exception.class})
    public AjaxResult refuse(Long id, String fileIds, String opinion, Long taskid, Long refuseNodeid, Long backUserid) {
        Materialretapply materialretapply = materialretapplyMapper.selectMaterialretapplyByNewId(id);

        SysUser sysUser = SecurityUtils.getLoginUser().getUser();

        materialretapply.setPlatformId(materialretapply.getStrmId());
        FlowResult result = processUtils.defaultRefuse(taskid, fileIds, opinion, materialretapply
                , sysUser, refuseNodeid, backUserid);

        if (result.getMsg().equals(ResultParam.SUCCESS)) {
            Materialretapply mApply = new Materialretapply();
            mApply.setStatus(result.getNextStat());
            mApply.setGuid(materialretapply.getGuid());
            this.updateMaterialretapply(mApply);
            return AjaxResult.success();
        } else {
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            return AjaxResult.error(result.getMsg());
        }
    }

    @Override
    @Transactional(propagation = Propagation.REQUIRED, rollbackFor = {Exception.class})
    public AjaxResult del(Long id) {
        SysUser sysUser = SecurityUtils.getLoginUser().getUser();
        Materialretapply materialretapply = materialretapplyMapper.selectMaterialretapplyByNewId(id);
        materialretapply.setStatus(0);
        this.updateMaterialretapply(materialretapply);
        //更新待处理任务
        processUtils.updateTaskByOrderId(id, sysUser, materialretapply.getFlowid());
        return AjaxResult.success();
    }

    @Override
    @Transactional(propagation = Propagation.REQUIRED, rollbackFor = {Exception.class})
    public AjaxResult inStoreroom(Materialretapply entity, String imgids, String opinion, Long taskid) {
        SysUser sysUser = SecurityUtils.getLoginUser().getUser();
        Materialretapply mater = materialretapplyMapper.selectMaterialretapplyByNewId(entity.getId());

        Pickinglist pick = pickinglistMapper.selectPickinglistById(mater.getLinkedid());

        /*BigDecimal nowWeight=new BigDecimal(0);
//        AjaxResult checkResult = AjaxResult.success();
        if(pick.getFlag()!=2){//自有生产的情况下 需要校验重量
            for(Matretapplyitem item:entity.getItems()){
                item.setShguid(item.getShrguid());
                Storehouseroom house = storehouseroomMapper.selectStorehouseroomById(item.getShguid());
                if(house.getShrtype()!=4){//辅料不参与计算
                    nowWeight=nowWeight.add(whoutformService.calculateWeight(item.getSpecguid(), item.getWeight(), null, 3).get("toT"));
                }
            }
            //校验重量
            try {
                checkResult=pickinglistService.checkWeight(mater.getLinkedid(), nowWeight);
            } catch (Exception e) {
                e.printStackTrace();
                return AjaxResult.error();
            }
        }*/

//        if((/*(checkResult.get(CODE_TAG)).equals(200)||*/pick.getFlag()==2)){//自有生产重量校验通过或者 代工生产 可直接入库
            AjaxResult resultIn = this.inStoreroom(entity,imgids);
            if((resultIn.get(CODE_TAG)).equals(200)){
                mater.setPlatformId(mater.getStrmId());
                FlowResult result = processUtils.defaultApproval(taskid, imgids, opinion, mater, sysUser);
                if (result.getMsg().equals(ResultParam.SUCCESS)) {
                    Materialretapply mApply = new Materialretapply();
                    mApply.setStatus(result.getNextStat());
                    mApply.setGuid(mater.getGuid());
                    this.updateMaterialretapply(mApply);
                    return AjaxResult.success();
                } else {
                    TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                    return AjaxResult.error(result.getMsg());
                }
            }else{
                return resultIn;
            }
//        }
//        return AjaxResult.error();
    }

    public AjaxResult inStoreroom(Materialretapply entity,String weightIds){
        SysUser sysUser = SecurityUtils.getLoginUser().getUser();

        entity.setLastupdate(new Date());
        entity.setStatus(2);
        materialretapplyMapper.updateMaterialretapplyID(entity);
        for (Matretapplyitem item : entity.getItems()) {
            matretapplyitemMapper.updateMatretapplyitem(item);
        }
        entity = materialretapplyMapper.selectMaterialretapplyByNewId(entity.getId());

        Whinform form = new Whinform();
        // 生成编码
        form.setDepartmentid(entity.getDepartid());
        form.setFormno(businesscodeService.getCode("4"));
        form.setBusinesscode(entity.getCode());
        form.setFoguid(entity.getGuid());
        form.setStorermguid(entity.getSrguid());
        form.setOperatorid(sysUser.getTuserId());
        form.setOrgguid(entity.getOrgguid());
        form.setOrgname(entity.getOrgname());
        form.setWhintype(6);

        Matretapplyitem matRetApplyItem = new Matretapplyitem();
        matRetApplyItem.setMatretapplyid(entity.getGuid());
        List<Whinformitem> whinformitems = new ArrayList<>();

        BigDecimal maWeight=BigDecimal.ZERO;
        for (Matretapplyitem item : matretapplyitemMapper.selectMatretapplyitemList(matRetApplyItem)) {
            maWeight=maWeight.add(item.getWeight());
            Whinformitem whinformitem = new Whinformitem();
            whinformitem.setWeight(item.getWeight());
            whinformitem.setSrguid(entity.getSrguid());
            whinformitem.setShrguid(item.getShguid());
            whinformitem.setProductguid(item.getProductid());
            whinformitem.setOrgguid(entity.getOrgguid());
            whinformitem.setOrgname(entity.getOrgname());
            whinformitem.setSpguid(item.getSpecguid());
            whinformitem.setStockunit(item.getStockunit());
            whinformitem.setStockunitid(item.getStockunitid());
            whinformitems.add(whinformitem);
        }

        String whinfoguid=whinformService.saveWhinfo(whinformitems, form);
        if(whinfoguid.equals("nospguid")){
            return AjaxResult.error("没有此规格");
        }
        return AjaxResult.success();
    }

    @Override
    public int countUNFinishMaterialret(String guid) {
        return materialretapplyMapper.countUNFinishMaterialret(guid);
    }

    @Override
    public BasePojo getBaseById(Long id) {
        return selectMaterialretapplyByNewId(id);
    }

    @Override
    public BasePojo getBaseByCode(String code) {
        return null;
    }
}
